/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    NativeModules,
    InteractionManager,
    Animated,
    TouchableWithoutFeedback
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import TopNavigator from '../components/TopNavigator';
import GoodsItem from '../components/GoodsItem';
import LeftPage from './LeftPage';
import StorageUser from '../lib/plugins/StorageUser';
import userService from '../lib/services/userService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');
export default class Message extends Component{
    constructor(props) {
        super(props);
        $this = this;
        this.token = '';
        this.userId = '';
        this.shopList = [];
        this.page = 1;
        this.blackPage;
        this.list = [];
        this.black = [];
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            staturs:props.staturs,
            checkedIndex:1,
            isOpen:false,
            blackIsOpen:false,
            groupIsOpen:false,
            blackList:ds.cloneWithRows(this.black),
            friendeArr:ds.cloneWithRows(this.list),
            messagePageList:[{name:'wesaws',project:'狗狗洗澡',time:'17.04.23-17.04.24'},{name:'ewre',project:'狗洗澡',time:'15.04.23-17.04.24'}],
            
            loadMore:true,
            blackLoadMore:true,
            groupData:{},
            shopName:'',
            shopId:'',
            shopImage:'',
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopName){
                    $this.setState({
                        shopName:data.shopName
                    })
                }
                if(data.shopList){
                    $this.shopList = data.shopList;
                }
                if(data.shopImage){
                    $this.setState({
                        shopImage:data.shopImage
                    })
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getFriendsList();
                    $this.getBlackList();
                    $this.getGroupList();
                });                
            }).catch(err=> {
                console.log(err)
            });
    }
    renderMessagePage(){
        return(
            this.state.messagePageList.map((item,i)=>{
                return(
                    <View key={i}>
                        <MessageItem name={item.name} project={item.project} time={item.time}/>
                    </View>
                )
            })
        )
    }
    renderItem(rowData,sectionID,rowID){
        return(
            <View>
                <PersonItem onPress={()=>this.goChatOne(rowData)} icon={{uri:'http://test.520m.com.cn/upload/thumb/'+rowData.user_head_img}} name={rowData.username}/>
            </View>
        )
    }
    friendList(){
        return(
            <View>
                <ListView
                    dataSource={this.state.friendeArr}
                    renderRow={(rowData,sectionID,rowID)=>this.renderItem(rowData,sectionID,rowID)}
                    enableEmptySections={true}
                    onEndReachedThreshold={1}
                    onEndReached={()=>this.getFriendsList()}/>
            </View>
        )
    }

    blackList(){
        return(
            <View>
                <ListView
                    dataSource={this.state.blackList}
                    renderRow={(rowData,sectionID,rowID)=>this.renderItem(rowData,sectionID,rowID)}
                    enableEmptySections={true}
                    onEndReachedThreshold={1}
                    onEndReached={()=>this.getBlackList()}/>
            </View>
        )
    }

    goChatOne(data){
        var id = data.friend_id + '';
        NativeModules.CommonModule.startChat(true,id,data.username)
    }
    goChatGroup(data){
        var id = data.id + '';
        NativeModules.CommonModule.startChat(false,id,data.name)
    }

    renderGroupList(){
        var obj = this.state.groupData;
        var list = [];
        list = list.concat(obj.create).concat(obj.admins).concat(obj.users);
        return(
            list.map((item,i)=>{
                return(
                    <View key={i}>
                        <PersonItem onPress={()=>this.goChatGroup(item)} icon={{uri:'http://test.520m.com.cn/upload/thumb/'+item.group_img}} name={item.name}/>
                    </View>
                )
            })
        )
    }
    showList(staturs,text){
        var func = null;
        var title = '';
        if(text=='friend'){
            func = this.friendList();
            title = '我的好友';
        }else if(text=='black'){
            func = this.blackList();
            title = '黑名单';
        }else if(text=='group'){
            func = this.renderGroupList();
            title = '俱乐部';
        }
        return(
            <View style={staturs?styles.hasBorder:styles.noBorder}>
                <TouchableOpacity onPress={()=>this.changeStaturs(text)}>
                    <View style={staturs?styles.openGroup:styles.closeGroup}>
                        <View style={{ height:40,flexDirection:'row',alignItems:'center',paddingLeft:10}}>
                            <View style={{flex:1}}>
                                <Text style={{color:'#151515'}}>{title}</Text>
                            </View>
                            <View style={{marginRight:10}}>
                                <ImageWrapper icon={staturs?'up':'down'}/>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
                {
                    staturs?func:null
                }
            </View>
        )
    }
    render(){
        return (
            <View style={styles.container}>
                <TopNavigator
                    messagePress={()=>this.chengeItem(1)}
                    peoplePress={()=>this.chengeItem(2)}
                    checkedIndex={this.state.checkedIndex}
                    chatPress={()=>this.goChat()}/>
                <ScrollView>
                    <View style={{backgroundColor:'#fff',borderBottomWidth:1,borderBottomColor:'#ccc'}}>
                        {this.state.checkedIndex==1?this.renderMessagePage():this.showList(this.state.isOpen,'friend')}
                        <View>
                            {this.state.checkedIndex==2?this.showList(this.state.blackIsOpen,'black'):<View></View>}
                            {this.state.checkedIndex==2?this.showList(this.state.groupIsOpen,'group'):<View></View>}
                        </View>
                    </View>

                </ScrollView>
                
            </View>
        )

    }
    showAnimate(){
        const {navigate } = this.props.navigation;
        navigate('LeftPage',{upData:(obj)=>{
            this.setState({
                shopName:obj.shopName,
                shopImage:obj.shopImage
            })
        }})
    }

    getFriendsList(){
        var $this = this;
        if(this.state.loadMore){
            userService.userFriendList(function(data){
                // alert(JSON.stringify(data))
                if(data.code==10000){
                    var arr = data.data.items;                    
                    $this.list = $this.list.concat(arr);
                    
                    if($this.page<data.data._meta.pageCount){
                        $this.page+=1;
                        $this.setState({
                            friendeArr:$this.state.friendeArr.cloneWithRows($this.list),
                            loadMore:true,
                        })
                    }else{
                        $this.setState({
                            friendeArr:$this.state.friendeArr.cloneWithRows($this.list),
                            loadMore:false,
                        })
                    }   
                }
            },0,$this.page,$this.token);
        } 
    }
    getBlackList(){
        var $this = this;
        if(this.state.blackLoadMore){
            userService.userFriendList(function(data){
                if(data.code==10000){
                    var arr = data.data.items;                    
                    $this.black = $this.black.concat(arr);
                    
                    if($this.blackPage<data.data._meta.pageCount){
                        $this.blackPage+=1;
                        $this.setState({
                            blackList:$this.state.blackList.cloneWithRows($this.black),
                            blackLoadMore:true,
                        })
                    }else{
                        $this.setState({
                            blackList:$this.state.blackList.cloneWithRows($this.black),
                            blackLoadMore:false,
                        })
                    }   
                }
            },1,$this.blackPage,/*'M5KX2JrPWSFw4PnLCukWkVcuokAJRX38'*/$this.token);
        } 
    }
    getGroupList(){
        var $this = this;
        userService.groupList(function(data){
            // alert(JSON.stringify(data))
            if(data.code==10000){
                
                $this.setState({
                    groupData:data.data
                })
            }
        },/*'M5KX2JrPWSFw4PnLCukWkVcuokAJRX38'*/$this.token)
    }
    changeStaturs(staturs){
        if(staturs=='friend'){
            this.setState({
                isOpen:!this.state.isOpen
            })
        }else if(staturs=='black'){
            this.setState({
                blackIsOpen:!this.state.blackIsOpen
            })
        }else if(staturs=='group'){
            this.setState({
                groupIsOpen:!this.state.groupIsOpen
            })
        }
        
    }

    chengeItem(item){
        this.setState({
            checkedIndex:item
        })
    }

    goChat(){
        NativeModules.CommonModule.openActivity("ConversationListActivity");
    }

}

class MessageItem extends Component{
    render(){
        return(
            <TouchableOpacity>
                <View style={{backgroundColor:'#fff',borderBottomWidth:1,borderBottomColor:'#E1E1E4',padding:10}}>
                    <View style={{height:30,justifyContent:'center'}}>
                        <Text style={{color:'#151515',fontSize:18}}>用户名 : {this.props.name}</Text>
                    </View>
                    <View style={styles.lineItem}>
                        <Text>预约项目 : {this.props.project}</Text>
                    </View>
                    <View style={styles.lineItem}>
                        <Text>预约时间 : {this.props.time}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }
}

class Group extends Component{
    renderList(){
        var list = this.props.list;
        var len = list.length-1;
        return(
            list.map((item,i)=>{
                return(
                    <View key={i}>
                        {i==len?
                            <PersonItem icon={item.img} name={item.name}/>:
                            <PersonItem icon={item.img} name={item.name}/>
                        }   
                    </View>
                )
            })
        )
    }
    render(){
        var isOpen = this.props.isOpen;
        return(
            <View style={isOpen?styles.hasBorder:styles.noBorder}>
                <TouchableOpacity onPress={this.props.onPress}>
                    <View style={isOpen?styles.openGroup:styles.closeGroup}>
                        <View style={[{ height:40,flexDirection:'row',alignItems:'center',paddingLeft:10},this.props.style]}>
                            <View style={{flex:1}}>
                                <Text style={{color:'#151515'}}>{this.props.text}</Text>
                            </View>
                            <View style={{marginRight:10}}>
                                <ImageWrapper icon={isOpen?'up':'down'}/>
                            </View>
                            
                        </View>
                    </View>
                </TouchableOpacity>
                {
                    isOpen?this.renderList():null
                }
            </View>
        )
    }
}

class PersonItem extends Component{
    render(){
        return(
            <TouchableWithoutFeedback onPress={this.props.onPress}>
                <View style={[{flexDirection:'row',marginLeft:20,alignItems:'center',height:40},this.props.style]}>
                    <View>
                        <ImageWrapper icon={this.props.icon} style={{borderRadius:20,marginRight:5}}/>
                    </View>
                    <View style={{flex:1}}>
                        <Text>{this.props.name}</Text>
                    </View>
                </View>
            </TouchableWithoutFeedback>
        )
    }
}
const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    lineItem:{
        height:26,
        justifyContent:'center'
    },
    openGroup:{
        backgroundColor:'#EEEEEE',
    },
    closeGroup:{
        backgroundColor:'#fff',
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    },
    hasBorder:{
        borderBottomWidth:1,
        borderBottomColor:'#ccc',
    },
    noBorder:{
        
    },
    icon: {
        width: 26,
        height: 26,
    },
    animateStyle:{
        width:7*width/10,
        height:height,
        position:'absolute',
        top:0,
        zIndex:10000,
        paddingBottom:20
    },
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.7)',
        justifyContent:'center',
        alignItems:'center',
    },
    
});